package com.webserver.core;

import com.webserver.http.HttpRequest;

import java.io.*;
import java.net.Socket;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.Map;

/**处理与指定客户端的HTTP交互
 * HTTP
 *
 */

public class ClientHandler implements Runnable {
    private Socket socket;

    public ClientHandler(Socket socket)  {
        this.socket = socket;
    }

    @Override
    public void run() {
        try {
            //1 解析请求
            HttpRequest request = new HttpRequest(socket);
            //2 处理请求
            String path = request.getUri();
            String line;
            File file = new File("./webapps"+path);
            if (file.exists()&&file.isFile()){
                //资源存在
                line = "HTTP/1.1 200 OK";
            }else {
                //资源不存在
                line = "HTTP/1.1 404 Notfound";
                file = new File("./webapps/root/404.html");
            }
            //输入的地址应该为：http://localhast:8088/myweb/index.html
            //或者http://localhost:8088/myweb/classTable.html

         /*
          ClientHandler在上一个版本中我们实现了将index.html页面响应的工作
           写法就是先实例化一个File对象表示index.html.具体代码：
          File file = new File(./webapps/myweb/index.html)
          如果我们想实现根据浏览器地址栏请求来响应不同页面，只需要
          */


            //发送响应头
            //将webpapps/myweb/index,html回复给浏览器

            /*HTTP/1.1 200 OK(CRLF)
            Content-Type: text/html(CRLF)
            Content-Length: 2546(CRLF)(CRLF)
                    1011101010101010101......*/
            OutputStream out = socket.getOutputStream();
            //3.1：发送状态行

            //UnsupportedEncodingException 原因：字符集名字拼写错误
            byte[] data = line.getBytes("ISO8859-1");
            out.write(data);
            out.write(13);  //written CR
            out.write(10);  //written LF

            //3.2:发送响应头
            line = "Content-Type: text/html";
            data = line.getBytes("ISO8859-1");  //转化为字符
            out.write(data);  //输出流写字符
            out.write(13); //written CR
            out.write(10);  //written LF


            line = "Content-Length: "+file.length();
            data = line.getBytes("ISO8859-1");  //
            out.write(data);
            out.write(13);
            out.write(10);

            //单独发送CRLF表示响应头发送完毕
            out.write(13);
            out.write(10);

            //3.3:发送正文（index页面内容）

            FileInputStream fis = new FileInputStream(file);  //读取文件
            byte[] buf = new byte[1024*8];  //建立字符数组用来循环保存字符
            int len; //整数来看文件是否读完
            while((len =fis.read(buf))!=-1){
                out.write(buf,0,len);
            }


            /*HTTP/1.1 200 OK(CRLF)
            Content-Type: text/html(CRLF)
            Content-Length: 2546(CRLF)(CRLF)
                    1011101010101010101......*/
                /*String line ="HTTP/1.1 200 OK";
                byte[] data = line.getBytes("ISO8859-1");
                out.write(data);
                out.write(13);
                out.write(10);

                data = "Content-Type: text/html(CRLF)";
           */
            //3 放送响应





        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                //交互完毕后与客户端断开
                socket.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }


    }



    private String readLine() throws IOException{
        InputStream in = socket.getInputStream();
        StringBuilder builder = new StringBuilder();
        int d;
        char pre = 'a',cur = 'a';
        while((d=in.read())!=-1){
            cur = (char)d;
            if (pre==13 && cur == 'a'){
                break;
            }
            builder.append(cur);
            pre = cur;
        }
        return  builder.toString().trim();
    }



}
            /*StringBuilder builder1 =new StringBuilder();
            char b;
            for (int i=0;i<line.length();i++){
                b=line.charAt(i);
                line.substring(i);
                if (b=='/'){
                    break;
                }
                method+=b;
            }
            for (int i=0;i<line.length();i++){
                b=line.charAt(i);
                line.substring(i);
                if (b=='/'){
                    break;
                }
                uri+=b;


            }*/